const Redis = require("ioredis");

const configPath =
  process.cwd() + `/config/config.${process.env.NODE_ENV || "dev"}.js`;
const config = require(configPath);

const redis = new Redis({
  port: config.redis.port || 6379,
  host: config.redis.host,
  password: config.redis.password || "610363806",
});

// 将数据添加到Redis有序集合中，使用id作为分数
storeDataToRedis = async (database_name, dataArray, key_id) => {
  for (const item of dataArray) {
    await redis.zadd(database_name, item[key_id], JSON.stringify(item));
  }
};

// 获取第page页的数据，每页size条记录
getPageData = async (database_name, limit) => {
  const start = (limit.page - 1) * limit.pageSize; // 计算起始分数
  const end = Math.min(
    start + limit.pageSize - 1,
    (await redis.zcard(database_name)) - 1
  ); // 计算结束分数，确保不超过总数

  const results = await redis.zrangebyscore(database_name, start, end, {
    withscores: true,
  });

  // 解析结果，将字符串转换回JavaScript对象
  const pageData = results
    .filter((_, index) => index % 2 === 0)
    .map(JSON.parse);

  return pageData;
};

module.exports = {
  redis,
  storeDataToRedis,
  getPageData,
};
